// subPages/communityService/shopContent/shopContent.js
const app = getApp();
var utils = require('../../../utils/util');
Page({
  /**
   * 页面的初始数据
   */
  data: {
    headBgColor:app.globalData.themeColor,
    leftNavList:[],
    goodsList:[],
    shoppingcartList:[],
    shoppingcartNum:0,
    popup:true,
    yunfei:0
  },

    /* 隐藏弹窗 */
    hidePopup(flag = true) {
        this.setData({
            "popup": flag
        });
    },
    /* 显示弹窗 */
    showPopup() {
        this.hidePopup(false);
    },
    buyNow(){
        let _this = this;
        if(_this.data.shoppingcartNum != 0){
            wx.navigateTo({
                url:'/subPages/communityService/shopConfirmOrder/shopConfirmOrder?id='+_this.data.shopId
            })
        }else{
            utils.showToast('请先加购物车，在进行支付','none',2000)
        }

    },
     /**
      * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
     console.log(options);
     utils.setNavBarTitle('超市')
      let that = this;
      this.setData({
          shopId:options.id
      });
     this.getMainHeight();
     this.getShopContentDetails();
     if(options.class_id){
         setTimeout(function(){
             let goodsid = options.goods_id;
             that.getShopProduct(options.id,options.class_id);
             that.setData({
                 currentId:options.class_id,
                 toView:'g'+goodsid
             })
         },500)
     }
    },
    
    onShow:function(){
        //获取商品分类,初始化商城
        this.getShopClass();
        //获取商品购物车
        this.getShoppingcart();
    },

    clacDatatime(){
        let _this = this;
        let now = new Date();
        let year = now.getFullYear();
        let month = now.getMonth()+1;
        let day = now.getDate();
        // shopInfo.open_time close_time
        let shopInfo = _this.data.shopInfo;
        let startDate = new Date(`${year}-${month}-${day} ${shopInfo.open_time}:00`);
        let closeDate = new Date(`${year}-${month}-${day} ${shopInfo.close_time}:00`);
        console.log(closeDate,startDate);
        let startTime = startDate.getTime()/1000;
        let closeTime = closeDate.getTime()/1000;
        let nowTime = now.getTime()/1000;
        if(nowTime >= startTime && nowTime<=closeTime ){
            console.log(1);
        }else{
            console.log('打烊');
        }
    },
    //获取超市详情
    getShopContentDetails(){
        let that = this;
        utils.getAjax(`${app.globalData.apiUrl}/get_community_service_shop_content`,function(res){
            // console.log(res);
            that.setData({
                shopInfo:res.data
            })
            that.clacDatatime();
        },{id:this.data.shopId})
    },
    //获取商城分类并初始化商城
    getShopClass:function(){
        let that = this;
        utils.getAjax(`${app.globalData.apiUrl}/get_community_service_shop_product_class`,function(res){
            // console.log(res.data == '');
            if(res.data != ''){
                that.setData({
                    leftNavList:res.data,
                    currentId:res.data[0].id
                })
                //获取初始化的商品列表
                that.getShopProduct(that.data.shopId,res.data[0].id);
            }else{
                wx.showModal({
                    title:'提示',
                    content:'店家暂停营业，给您带来的麻烦，请谅解！',
                    showCancel:false,
                    success(res) {
                        if (res.confirm) {
                            // console.log('用户点击确定')
                            wx.navigateBack({delete :-1})
                        } else if (res.cancel) {
                            console.log('用户点击取消')
                        }
                    }
                })
            }
        },{shop_id:that.data.shopId});
    },
    getTab(){
      let that = this;
      let goodsList = that.data.goodsList;
      let shoppingcartList = that.data.shoppingcartList;
        // console.log(goodsList,shoppingcartList);
        for(let i=0;i<goodsList.length;i++){
          for(let j=0;j<shoppingcartList.length;j++){
              if(goodsList[i].id == shoppingcartList[j].product_content.id){
                  goodsList[i].buy_num = shoppingcartList[j].num
              }
          }

      }
      that.setData({
          goodsList:goodsList
      })
    },
    //获取购物车数据
    getShoppingcart(){
        let that = this;
        utils.getAjax(`${app.globalData.apiUrl}/get_user_community_service_shop_product_buycar`,function(res){
            console.log(res);
            if(res.data.length == 0){
                that.hideModal();
            }
            that.setData({
                shoppingcartList:res.data,
                shoppingcartNum:res.data.length
            })
            that.getTab();
            that.getTotalMoney();
        },{shop_id:that.data.shopId,user_id: app.globalData.userId})
    },

    //获取分类的产品
    getShopProduct(shopId,classId){
        let that = this;
        utils.getAjax(`${app.globalData.apiUrl}/get_community_service_shop_product`,function (res) {
            for(let i=0;i<res.data.length;i++){
                res.data[i].buy_num = 0;
            }
            that.setData({
                goodsList:res.data
            })
            that.getTab();
        },{shop_id:shopId,class_id:classId})
    },
    getMainHeight(){
        let that = this;
          let winHeight = '';
          wx.getSystemInfo({
              success(res) {
                  // console.log(res.windowHeight)
                  winHeight = res.windowHeight;
              }
          })
        let query = wx.createSelectorQuery();
        let topHeight = '';
        query.select('.shop-top-box').boundingClientRect(rect=>{
            console.log(rect);
            topHeight = rect.height;
        }).exec();
        let bottomHeight = '';
        query.select('.bottom-bar').boundingClientRect(rect=>{
            bottomHeight = rect.height;
        }).exec();
        setTimeout(function () {
            let mainHeight = winHeight - 50 - topHeight - bottomHeight;
            that.setData({
                mainHeight:mainHeight
            })
        },200)
    },
    selectItem(e){
      let itemId = e.currentTarget.dataset.id;
      let that = this;
      this.setData({
          currentId:itemId
      })
      that.getShopProduct(that.data.shopId,itemId)
    },
    //加入购物车
    addToShoppingcart(e){
        let that = this;
        if(app.globalData.userId){
            var goodsId = e.currentTarget.dataset.id;
            let goodsList = that.data.goodsList;
            let price;
            let num;
            for(let i=0;i<goodsList.length;i++){
                if(goodsList[i].id == goodsId){
                    price = goodsList[i].price;
                    goodsList[i].buy_num = parseInt(goodsList[i].buy_num)+1;
                    num = goodsList[i].buy_num;
                }
            }
            utils.getAjax(`${app.globalData.apiUrl}/operation_community_service_shop_product_buycar`,function(res){
                    // console.log(res);
                    that.getShoppingcart();
                },
                {
                    type:1,
                    shop_id:that.data.shopId,
                    product_id:goodsId,
                    user_id:app.globalData.userId,
                    num:num,
                    price:price
                })
        }else{
            utils.showModelAll('提示','该功能需要授权登录后使用，请进行授权登录',function(){
                if (app.globalData.userInfo) {
                    //已授权
                    wx.redirectTo({
                        url: '/pages/login/login'
                    })
                }else{
                    // 在没有 open-type=getUserInfo 版本的兼容处理
                    if(app.globalData.isAuthorized){
                        app.userInfoReadyCallback = res => {
                          if (res) {
                            //已授权
                            wx.redirectTo({
                              url: '/pages/login/login'
                            })
                          }else{
                            //未授权
                            wx.navigateTo({
                              url: '/pages/authorizedLogin/authorizedLogin?isLogin='+ false,
                            })
                          }
                        }
                    }else{
                        wx.navigateTo({
                          url: '/pages/authorizedLogin/authorizedLogin?isLogin='+ false,
                        })
                    }
                }
            })
        }
    },
    //购物车减少
    reduceShoppingcart(e){
        let orderId = e.currentTarget.dataset.id,
            that = this,
            num,price;
        // console.log(orderId);
        let shoppingcartList = that.data.shoppingcartList;
        for(let i=0;i<shoppingcartList.length;i++){
            if(shoppingcartList[i].id == orderId){
                num = shoppingcartList[i].num-1;
                price = shoppingcartList[i].price;
                // console.log(num,price);
                utils.getAjax(`${app.globalData.apiUrl}/operation_community_service_shop_product_buycar`,function(res){
                    that.getShoppingcart();
                    that.getShopClass();
                },{
                    type:2,
                    id:orderId,
                    num:num,
                    price:price
                })

            }

        }
    },
    getTotalMoney(){
      let that = this;
      let shoppingcartList = that.data.shoppingcartList;
      let totalMoney = 0;
      for(let i in shoppingcartList){
      // for(let i=0;i<shoppingcartList.length;i++){
          totalMoney += shoppingcartList[i].num * shoppingcartList[i].price
      }

     that.setData({
       totalMoney:totalMoney.toFixed(2)
     })

    },
    //清空购物车
    clearShoppingcart(){
        let that = this;
        utils.showModelAll('清空购物车','您是否确定删除购物车？',function(){
            utils.getAjax(`${app.globalData.apiUrl}/operation_community_service_shop_product_buycar`,function(res){
                    console.log(res);
                    if(res.data == 1){
                        that.hideModal();
                        utils.showToast('已清空','none',1000);
                        that.getShoppingcart();
                        that.getShopClass();
                    }
                },
                {
                    type:3,
                    shop_id:that.data.shopId,
                    user_id:app.globalData.userId,
                })
        })


    },
    shoppingcartAdd(e){
        var goodsId = e.currentTarget.dataset.id;
        console.log(goodsId);
        var that = this,
        shoppingcartList = that.data.shoppingcartList,
        num,price;

        for(var i=0;i<shoppingcartList.length;i++){
            if(shoppingcartList[i].product_content.id == goodsId){
                num = parseInt(shoppingcartList[i].num)+1;
                shoppingcartList[i].num = shoppingcartList[i].num+1;
                price = shoppingcartList[i].price;
            }
        }
        utils.getAjax(`${app.globalData.apiUrl}/operation_community_service_shop_product_buycar`,function(res){
                // console.log(res);
                that.getShoppingcart();
            },
            {
                type:1,
                shop_id:that.data.shopId,
                product_id:goodsId,
                user_id:app.globalData.userId,
                num:num,
                price:price
            })
    },

    //弹框
    clickModal(){
        let that = this;
        if(that.data.shoppingcartList.length == 0){
            utils.showToast('请先添加商品','none',2000);
            return
        }
          if(this.data.showModalStatus){
              this.hideModal();
          }else{
              this.showModal();
          }
    },
    showModal: function () {
    // 显示遮罩层
    var animation = wx.createAnimation({
        duration: 200,
        timingFunction: "linear",
        delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
        animationData: animation.export(),
        showModalStatus: true
    })
    setTimeout(function () {
        animation.translateY(0).step()
        this.setData({
            animationData: animation.export()
        })
    }.bind(this), 200)
},
    hideModal: function () {
    // 隐藏遮罩层
    var animation = wx.createAnimation({
        duration: 200,
        timingFunction: "linear",
        delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
        animationData: animation.export(),
    })
    setTimeout(function () {
        animation.translateY(0).step()
        this.setData({
            animationData: animation.export(),
            showModalStatus: false
        })
    }.bind(this), 200)
},

})
